package com.ljy.my_study.spring.tiny.study8.beans.factory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ljy.my_study.spring.tiny.study7.beans.BeanDefinition;

public abstract class AbstractBeanFactory implements BeanFactory{
	
	private Map<String,BeanDefinition> beanDefinitionMap=new HashMap<>();
	
	private List<String> beanDefinitionNames=new ArrayList<>();

	@Override
	public Object getBean(String name) throws Exception {
		BeanDefinition beanDefinition=beanDefinitionMap.get(name);
		if(beanDefinition==null) {
			throw new IllegalArgumentException("No bean names "+name+" is defined.");
		}
		Object bean=beanDefinition.getBean();
		if(bean==null) {
			bean=doCreateBean(beanDefinition);
		}
		return bean;
	}
	
	public abstract Object doCreateBean(BeanDefinition beanDefinition) throws Exception;
	
	public void registerBeanDefinition(String name,BeanDefinition beanDefinition) {
		beanDefinitionMap.put(name,beanDefinition);
		beanDefinitionNames.add(name);
	}
	
	public void proInstantiateSingletons() throws Exception {
		for(Iterator<String> it=beanDefinitionNames.iterator();it.hasNext();) {
			String name=it.next();
			getBean(name);
		}
	}
}
